package com.blockmeta.bbs.minemodule.activity;

import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import okhttp3.Call;

/**
 * @author airthor
 * @date 2018/09/11
 * 推送管理
 */
public class PushManagerActivity extends BaseActivity {


    @BindView(R2.id.toggle_market)
    ToggleButton mToggleMarket;
    @BindView(R2.id.toggle_fast_news)
    ToggleButton mToggleFastNews;
    @BindView(R2.id.toggle_forum_news)
    ToggleButton mToggleForumNews;
    @BindView(R2.id.tv_tag_state)
    TextView mTvTagState;

    private static final String MARKET = "ipm";
    private static final String INTERACT = "ipi";
    private static final String NEWS = "ipn";
    //开关是否是通过手指触摸触发的
    private boolean isTriggeredByTouch = true;
    //记录推送通知是否都被关闭，此处通过位运算实现
    private int STATE = 7;
    private int MARKET_STATE=1;
    private int NEWS_STATE = 2;
    private int INTERACT_STATE = 4;

    @Override
    protected boolean showTitle() {
        setTitleText("推送管理");
        return true;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_push_manager, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        getInitialState();
    }

    @OnCheckedChanged({R2.id.toggle_market,R2.id.toggle_fast_news,R2.id.toggle_forum_news})
    void onCheckedChange(CompoundButton button,boolean isChecked){
        if (!isTriggeredByTouch){
            isTriggeredByTouch = true;
            return;
        }
        int i = button.getId();
        if (i == R.id.toggle_market) {
            taskDistributing(MARKET, isChecked);

        } else if (i == R.id.toggle_fast_news) {
            taskDistributing(NEWS, isChecked);

        } else if (i == R.id.toggle_forum_news) {
            taskDistributing(INTERACT, isChecked);
        }
    }

    /**
     * 任务分发
     * @param tag 只能选择 ipi,ipm,ipn中的一个分别对应忽略互动消息、行情消息、资讯消息
     * @param isCheck true为接收 false为不接收
     */
    private void taskDistributing(String tag,Boolean isCheck) {
        if (isCheck){
            openPush(tag);
        }else {
            closePush(tag);
        }
    }

    private void openPush(final String tag) {
        ProgressBarUtil.showProgress(this);
        String url = String.format(NetConstant.PUSH_MANAGER,tag);
        String uid = AccountHelper.getUid();
        String token = SharedPreferenceUtil.getString(this, Constant.TOKEN,"");
        OkHttpUtils.delete()
                .addHeader("token",token)
                .addHeader("uid",uid)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                        resetCheckedState(tag);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                        getResultState(tag,true);
                    }
                });
    }

    private void closePush(final String tag){
        ProgressBarUtil.showProgress(this);
        String url = String.format(NetConstant.PUSH_MANAGER,tag);
        String uid = AccountHelper.getUid();
        String token = SharedPreferenceUtil.getString(this,Constant.TOKEN,"");
        OkHttpUtils.post()
                .addHeader("token",token)
                .addHeader("uid",uid)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                        resetCheckedState(tag);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                        getResultState(tag,false);
                    }
                });
    }

    /**
     * 当改变推送状态的接口请求失败后要重置状态为前一个状态
     */
    private void resetCheckedState(String tag){
        isTriggeredByTouch = false;
        switch (tag){
            case MARKET:
                mToggleMarket.setChecked(!mToggleMarket.isChecked());
                break;
            case NEWS:
                mToggleFastNews.setChecked(!mToggleFastNews.isChecked());
                break;
            case INTERACT:
                mToggleForumNews.setChecked(!mToggleForumNews.isChecked());
                break;
            default:
                break;
        }
    }

    private void getResultState(String tag,boolean isChecked){
        int current;
        switch (tag){
            case MARKET:
                current = MARKET_STATE;
                break;
            case NEWS:
                current = NEWS_STATE;
                break;
            case INTERACT:
                current = INTERACT_STATE;
                break;
            default:
                current = -1;
                break;
        }
        if (current==-1) {return;}
        if (isChecked){
            STATE = STATE|current;
        }else {
            STATE = STATE^current;
        }
        if (STATE == 0){
            mTvTagState.setText("未开启");
        }else {
            mTvTagState.setText("已开启");
        }
    }

    private void getInitialState(){
        ProgressBarUtil.showProgress(this);
        String url = String.format(NetConstant.PUSH_MANAGER,"tags");
        String uid = AccountHelper.getUid();
        String token = SharedPreferenceUtil.getString(this,Constant.TOKEN,"");
        OkHttpUtils.get()
                .addHeader("token",token)
                .addHeader("uid",uid)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(PushManagerActivity.this);
                        String[] result = new Gson().fromJson(response,String[].class);
                        if (result.length == 0){
                            mTvTagState.setText("已开启");
                        }
                        for (int i = 0; i < result.length; i++) {
                            if (MARKET.equals(result[i])){
                                isTriggeredByTouch = false;
                                mToggleMarket.setChecked(false);
                                getResultState(MARKET,false);
                            }else if (NEWS.equals(result[i])){
                                isTriggeredByTouch = false;
                                mToggleFastNews.setChecked(false);
                                getResultState(NEWS,false);
                            }else if (INTERACT.equals(result[i])){
                                isTriggeredByTouch = false;
                                mToggleForumNews.setChecked(false);
                                getResultState(INTERACT,false);
                            }
                        }
                    }
                });
    }
}
